// import api from './webapi';
import { defineStore } from 'pinia';
import yy from '@lib/mixin';
const { ipcRenderer } = window['require']('electron');

function storage(key: any, value: any = "", type: any = "") {
  if (type) {
    localStorage.removeItem(key);
    return;
  } else {
    if (!!value) {
      return localStorage.setItem(key, JSON.stringify(value));
    } else {
      let val = localStorage.getItem(key) || "";
      return (val && JSON.parse(val)) || "";
    }
  }
}

// 处理边界数据
function processTTSBoundaries(boundaryData, fanyi) {


  let words: any = [];
  const sentences: any = [];

  boundaryData.forEach(item => {
    if (item.Type === "WordBoundary") {
      words.push({
        text: item.Data.text.Text,
        start: item.Data.Offset / 10000000,
        end: (item.Data.Offset + item.Data.Duration) / 10000000,
        duration: item.Data.Duration,
        off: item.Data.Offset
      });
    } else if (item.Type === "SentenceBoundary") {
      sentences.push({
        off: item.Data.Offset,
        text: item.Data.text.Text,
        start: item.Data.Offset / 10000000,
        end: (item.Data.Offset + item.Data.Duration) / 10000000,
        duration: item.Data.Duration,
        len: item.Data.text.Text.replace(/[.。]/g, '').replace(/\s/g, ',').split(',').length,
        words: []
      });
    }
  });

  words = words.sort((a, b) => { a.off - b.off });
  let fy = fanyi.replace(/[!！。.?]/g, ',').split(',');
  // // 将单词分配到句子中
  // let index = 0;
  sentences.forEach((sentence, i) => {
    sentence.cns = fy[i];
    sentence.words = words.filter(word => {
      return word.off >= sentence.off && (word.off + word.duration <= sentence.off + sentence.duration)
    })
  });
  return {
    words: words,
    sentences: sentences
  };
}
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export default defineStore('main', {
  state: () => {
    let audio: any;
    return {
      isAdmin: true,
      gonlishu: storage("gonlishu") || 0,
      ttsConfig: storage('ttsConfig'),
      voiceList: storage('voiceList'),
      nameList: storage('nameList'),
      fileUrl: storage('fileUrl') || 'C:/xiaoxuebao/',
      screenList: [],
      isScreen: false,
      isConfig: false,//全局设置
      play: {
        url: "",
      },
      heji: {},
      isPic: '',
      audio: audio,
      showFanyi: false,
      rDetail: {
        isRoter: true,
        msg: ''
      }
    }
  },
  actions: {
    speek(msg, config = { auto: true, isFile: false }) {
      if (!msg.length) {
        yy.msg({ message: '单词或文本不为空！', type: "error" });
        return
      }
      if (this.audio) {
        this.audio.pause();
        this.audio = null;
      }
      // console.log(msg, this.ttsConfig);

      return ipcRenderer.invoke('tts-speek', { message: msg, ...this.ttsConfig, ...config }).then(res => {
        console.log(res, '=================')
        if (config.auto) {
          this.audio = new Audio(URL.createObjectURL(new Blob(res.bufferList, { type: 'audio/webm' })));
          this.audio.play()
        }
        return {
          url: URL.createObjectURL(new Blob(res.bufferList, { type: 'audio/webm' })),
          ...processTTSBoundaries(res.buffer.map(v => JSON.parse(v)?.Metadata[0]), res.fanyi)
        }
      })
    },
    toSpeek(msg, config = {}) {
      if (!msg.length) {
        yy.msg({ message: '单词或文本不为空！', type: "error" });
        return
      }
      if (this.audio) {
        this.audio.pause();
        this.audio = null;
      }
      return ipcRenderer.invoke("toSpeek", { message: msg, ...this.ttsConfig, ...config }).then(res => {
        this.audio = new Audio(URL.createObjectURL(new Blob(res, { type: 'audio/webm' })));
        this.audio.play()
        return res.length > 0;
      })
    },
    getHistoryTTS(path) {
      return ipcRenderer.invoke('get-history-tts', { path }).then(res => {
        return {
          url: URL.createObjectURL(new Blob(res.bufferList, { type: 'audio/webm' })),
          ...processTTSBoundaries(res.buffer.map(v => JSON.parse(v)?.Metadata[0]), res.fanyi)
        }
      })
    },
    run(data) {
      return ipcRenderer.invoke('mysql');
    },
    invoke(name, data) {
      return ipcRenderer.invoke(name, data);
    },
    sql(data) {
      return ipcRenderer.invoke('words', data)
    }
  },
})